<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools>
        <el-button v-if="$check('POING-USER-EXPORT')" size="small" type="danger" @click="exportExcel">导出</el-button>
        <el-button v-if="$check('POINT-USER-IMPORT')" size="small" type="primary" @click="$router.push('/import?type=employees')">导入</el-button>
        <el-button v-if="$check('POINT-USER-ADD')" size="small" icon="el-icon-plus" type="primary" @click="showadd = true">新增员工</el-button>
      </PageTools>

      <el-card style="margin-top:20px">
        <el-table
          :data="tableData"
          border
          style="width: 100%"
        >
          <el-table-column
            fixed
            prop="date"
            type="index"
            label="序号"
            :index="showindex"
          />
          <el-table-column
            prop="username"
            label="姓名"
          />
          <el-table-column
            prop="username"
            label="头像"
            align="center"
          >
            <template v-slot="{row}"><img
              v-imgerror="require('@/assets/common/bigUserHeader.png')"
              style="width: 100px; height: 100px; border-radius:50%"
              :src="row.staffPhoto"
            ></template>

          </el-table-column>
          <el-table-column
            prop="mobile"
            label="手机号"
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            sortable
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
            :formatter="formatEmployment"
          />
          <el-table-column
            prop="departmentName"
            label="部门"
          />

          <el-table-column
            label="入职时间"
            prop="timeOfEntry"
            align="center"
            sortable
          >
            <template v-slot="{row}">
              {{ row.timeOfEntry | moment }}
            </template>
          </el-table-column>
          <el-table-column
            label="账户状态"
            prop="enableState"
            align="center"
          >
            <template v-slot="{row}">
              <el-switch
                v-model="row.enableState"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
              />
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            label="操作"
            width="280"
            align="center"
          >
            <template v-slot="{row}">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delrole(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          style="float:right"
          background
          :current-page="page"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="size"
          layout="total, sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-card>
      <AddEmployee :showadd="showadd" @showaddoff="showaddoffFn" />

      <AssignRole :show-role-dialog="showRoleDialog" :user-id="userId" @offshow="offshowFn" />
    </div>
  </div>
</template>

<script>
import AssignRole from './components/assign-role.vue'
import employees from '@/components/constant/employees'
import { getallempoyeesRes, delempoyeesRes } from '@/api/employees'
import AddEmployee from './components/AddEmployee.vue'
import moment from 'moment'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      showRoleDialog: false,
      tableData: [],
      total: 0,
      size: 5,
      page: 1,
      showadd: false,
      userId: ''
    }
  },
  computed: {

  },
  created() {
    this.getallempoyees()
  },
  methods: {
    // 获取默认数据
    async getallempoyees() {
      const res = await getallempoyeesRes({ page: this.page, size: this.size })
      this.tableData = res.rows

      this.total = res.total
    },
    // 改变当前页
    async handleCurrentChange(value) {
      this.page = value
      this.$nextTick()
      await this.getallempoyees()
    },
    // 改变序号的排列
    showindex(index) {
      return index + 1 + (this.page - 1) * this.size
    },
    // 改变每页的数量
    async handleSizeChange(value) {
      this.size = value
      this.$nextTick()
      await this.getallempoyees()
    },
    // 删除某角色
    async delrole(id) {
      try {
        await this.$confirm('你确定要删除该员工吗', '温馨提示', {
          type: 'warning'
        })
      } catch {
        return
      }
      if (this.tableData.length === 1 && this.page > 1) {
        this.page--
      }
      await delempoyeesRes(id)
      this.getallempoyees()
    },

    // 格式化聘用形式
    formatEmployment(row, column, cellValue, index) {
      const obj = employees.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : ''
    },
    // 关闭add框
    showaddoffFn() {
      this.getallempoyees()
      this.showadd = false
    },
    // 导出员工
    exportExcel() {
      this.downloadLoading = true
      // 异步导入的目的：提高性能，只要用到导出功能的时候，才会去加载导出的js
      import('@/vendor/Export2Excel').then(async excel => {
        const headers = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        const header = Object.keys(headers)
        const { rows } = await getallempoyeesRes({ page: 1, size: this.total })
        const data = rows.map(item => {
          const arr = []
          header.forEach(k => {
            if (k === '入职日期' || k === '转正日期') {
              arr.push(moment(item[headers[k]]).format('YYYY-MM-DD'))
            } else if (k === '聘用形式') {
              const res = employees.hireType.find(ids => {
                return ids.id === item[headers[k]]
              })
              arr.push(res ? res.value : '')
            } else {
              arr.push(item[headers[k]])
            }
          })
          return arr
        })

        excel.export_json_to_excel({
        // 表头
          header,
          // 数据
          data,
          // 文件名
          filename: 'test',
          // 自动宽度
          autoWidth: true,
          // 后缀名
          bookType: 'xlsx'
        })
        this.downloadLoading = false
      })
    },
    // 展示分配角色页面
    showRole(id) {
      this.showRoleDialog = true
      this.userId = id
    },
    offshowFn() {
      this.showRoleDialog = false
    }
  }

}
</script>

<style>

</style>

